<template>
  <div>
    <div class="container">
      <div class="handle-box">

        <el-button
          type="primary"
          icon="el-icon-delete"
          class="handle-del mr10"
          @click="delAllSelection"
        >批量删除
        </el-button>

        <el-input v-model="query.phone" placeholder="联系方式" class="handle-input mr10"></el-input>
        <el-input v-model="query.idcard" placeholder="身份证" class="handle-input mr10"></el-input>

        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="handleAdd()">新建</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="exportExcel()">导出用户信息</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="addExcel()">Excel导入</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="ExcelInstall()">下载模板</el-button>

      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="phone" label="联系方式"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="sex" label="性别">
          <template slot-scope="scope">{{ scope.row.sex === 0 ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建日期"
          :formatter="dateFormat"
          align="center"
        ></el-table-column>
        <!--        <el-table-column prop="roleId" label="权限"></el-table-column>-->

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.role =='用户'?false:true"
                       type="text"
                       icon="el-icon-delete"
                       class="red"
                       @click="handleDelete(scope.$index, scope.row)"
            >删除
            </el-button>
            <el-button
              type="text"
              icon="el-icon-search"
              @click="handleSelect(scope.row)"
            >查询
            </el-button>
            <!--                        用户状态更改-->
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index,scope.row)"
            >编辑
            </el-button>
            <!--            <va-button flat small color="gray" @click="edit(scope.rowData)" class="ma-0">-->
            <!--              编辑-->
            <!--            </va-button>-->

            <el-button
              type="text"
              icon="el-icon-folder"
              @click="exportPDF(scope.$index,scope.row)"
            >导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="size"
          @current-change="getData">
        </el-pagination>
      </div>
    </div>
    <!--新建弹出框-->
    <el-dialog title="新建" :modal="false" :visible.sync="addVisible" width="50%">
      <el-form
        ref="add"
        :model="add"
        label-width="80px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="add.username"></el-input>

        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input :placeholder="add.password" v-model="add.password"></el-input>
        </el-form-item>
        <!--    <el-form-item  label="确认密码" prop="repassword">-->
        <!--    @blur="getName(add.idcard)"        <el-input :placeholder="add.repassword" v-model="add.password"></el-input>-->
        <!--          </el-form-item>-->
        <el-form-item label="身份证" prop="idcard">
          <el-input v-model="add.idcard"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="add.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="add.age"></el-input>
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="add.occupation"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="add.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="add.email"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd('add')">确 定</el-button>
      </span>
    </el-dialog>

    <!--        查询-->
    <el-dialog title="详细信息" :modal="false" :visible.sync="selectVisible" width="70%">
      <el-table :data="tableData">
        <el-table-column property="id" label="ID" width="150"></el-table-column>
        <el-table-column property="username" label="姓名" width="200"></el-table-column>
        <el-table-column property="idcard" label="身份证" width="200"></el-table-column>
        <el-table-column property="occupation" label="职业" width="200"></el-table-column>
        <el-table-column property="birthday" label="出生日期" width="200"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selectVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :modal="false" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px" :rules="rules2">
        <!--        <el-form-item label="ID">-->
        <!--          <el-input v-model="form.id" :disabled="true"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="用户名" prop="id">
          <el-input v-model="form.id"></el-input>
        </el-form-item>
        <el-form-item label="权限:" :label-width="formLabelWidth" prop="roleId">
          <el-select v-model="form.roleId" autocomplete="off">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="用户" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
      </span>
    </el-dialog>

    <!--        导入excel-->
    <el-dialog
      title="导入excel"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-upload
        class="upload-demo"
        drag
        :on-success="uploadAfter"
        action="http://8.135.35.123:9000/hotelsystem/user/impUser"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过500kb</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
            </span>
    </el-dialog>

  </div>
</template>

<script>
  import { list } from '../../network/usermanage'
  import valrule from '../../config/validaterule'
  import { saveuser } from '../../network/adduser'
  import { userdelete } from '../../network/userdelete'
  import { pdfUser } from '../../network/exportPDF'
  import { search } from '../../network/search'
  import {userview } from '../../network/userview'
  import moment from '../../config/moment'
  import { updateRole } from '../../network/changeUserStatus'

  export default {
    name: 'usermanage',
    data () {
      return {
        formLabelWidth: '298.3',
        rules: {
          username: [{
            required: true,
            message: '用户名',
            trigger: 'blur',
          }],
          password: [{
            required: true,
            message: '密码',
            trigger: 'blur',
          }],

          phone: [{
            required: false,
            message: '联系方式',
            trigger: 'blur',
            validator: valrule.validPhone,
          }],
          email: [{
            required: false,
            trigger: 'blur',
            validator: valrule.validEmail,
          }],
          occupation: [{
            required: true,
            trigger: 'blur',
          }],
          idcard: [{
            required: true,
            trigger: 'blur',
          }],
        },
        rules2: {
          username: [{
            required: true,
            message: '用户名',
            trigger: 'blur',
          }],
          role_id: [{
            required: true,
            message: '权限',
            trigger: 'blur',
          }],
        },

        // 查询的相关参数
        query: {
          idcard: '',
          phone: '', // 用户名
          pageIndex: 1, // 当前请求页
          size: 5, // 一页显示的数据条数
        },

        // 添加相关参数
        add: {
          age: '',
          // avatar: '',
          // birthday: '',
          // createTime: '',
          email: '',
          // id: '',
          idcard: '',
          occupation: '',
          password: '',
          phone: '',
          // role: '',
          // roleId: '',
          sex: '',
          // sexText: '',
          username: '',
          dialogVisible: false,
        },

        message: {

          username: '',
          age: '',
          createTime: '',
          email: '',
          phone: '',
          occupation: '',
          birthday: '',
          idcard: '',

        },
        tableData: [], // 获取的数据
        multipleSelection: [],
        delList: [],
        editVisible: false, // 编辑弹出框false隐藏，true显示
        addVisible: false, // 新建弹出框false隐藏，true显示
        dialogVisible: false,
        total: 0,
        size: 10,
        currentPage: 1,
        form: {},
        user: {},
        idx: -1,
        id: -1,
        selectVisible: false,
      }
    },
    created () {
      this.getData()
    },
    methods: {

      addExcel () {
        this.dialogVisible = true
      },
      uploadAfter () {
        this.getData()
      },
      handleClose (done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {
          })
      },
      // // 新编辑
      // edit (checkData) {
      //   this.$router.push({
      //     name: 'user-mod',
      //     params: checkData,
      //   })
      // },

      dateFormat: function l (el) {
        return moment(el).format('YYYY-MM-DD')
      },
      getName (iden) {
        const val = iden.length
        let sex = null
        const myDate = new Date()
        const month = myDate.getMonth() + 1
        const day = myDate.getDate()
        let age = 0

        if (val === 18) {
          age = myDate.getFullYear() - iden.substring(6, 10) - 1
          sex = iden.substring(16, 17)
          if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++
        }
        if (val === 15) {
          age = myDate.getFullYear() - iden.substring(6, 8) - 1901
          sex = iden.substring(13, 14)
          if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++
        }

        if (sex % 2 === 0) {
          sex = 1
        } else {
          sex = 0
        }
        this.add.sex = sex
        this.add.age = age

        this.getDataInfo()
      },

      update () {
        this.add.password = '123'
      },

      // query表单参数判空,如果参数为空字符串或null等则不发送请求
      queryIsNull () {
        const queryForm = {
          // id: this.query.id, //部门id
          name: this.query.username, // 部门名称
          pageIndex: this.query.pageIndex, // 当前请求页
          size: this.query.size, // 一页显示的数据条数
        }

        if (this.query.id.split(' ').join('').length !== 0 && this.query.id !== null && this.query.id !== undefined) {
          // alert('id不为空');
          queryForm.id = this.query.id
        } else {
          // alert('id为空');
        }

        if (this.query.name(' ').join('').length !== 0 && this.query.name !== null && this.query.name !== undefined) {
          // alert('id不为空');
          queryForm.name = this.query.username
        } else {
          alert('name为空')
        }

        return queryForm
      },

      // 初始化数据
      getData (currentPage) {
        console.log('表单')
        list(currentPage)
          .then((res) => {
            console.log(res)
            if (res.data.code === 80200) {
              console.log(res)
              this.tableData = res.data.data.records
              this.tableData.forEach(item => {
                item.status = Boolean(item.status)
              })

              this.total = res.data.data.total
              this.size = res.data.data.size
              this.currentPage = res.data.data.current
            } else {
              this.$message.error('数据获取失败，' + res.data.data.msg)
            }
          })
          .catch(() => {
            this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确')
          })
      },
      exportExcel () {
        window.location.href = 'http://8.135.35.123:9000/hotelsystem/user/export'
      },

      ExcelInstall () {
        window.location.href = 'http://8.135.35.123:9000/hotelsystem/user/install'
      },
      exportPDF (index, row) {
        // 二次
        this.$confirm('确定要导出吗？', '提示', {
          type: 'warning',
        }).then(() => {
          // alert(row.id)

          window.location.href = 'http://8.135.35.123:9000/hotelsystem/user/pdfuser?id=' + row.id
        })
      },

      // 新建操作
      handleAdd () {
        // alert("即将进入新建页面")
        this.addVisible = true
      },

      // 保存新建
      saveAdd (add) {
        console.log('添加')
        console.log(this.add)
        this.$refs[add].validate((valid) => {
          if (valid) {
            this.addVisible = false
            let formData = new FormData();
            formData.append('age',this.add.age)
            formData.append('email',this.add.email)
            formData.append('idcard',this.add.idcard)
            formData.append('username',this.add.username)
            formData.append('password',this.add.password)
            formData.append('occupation',this.add.occupation)
            formData.append('sex',this.add.sex)
            formData.append('phone',this.add.phone)
            saveuser(formData)
              .then((res) => {
                console.log(res)
                if (res.data.code === 80200) {
                  this.$message.success('新建用户成功')
                  this.getData()
                } else {
                  this.$message.error('新建用户失败')
                  // this.getData();
                }
                this.addVisible = false
              })
              .catch(() => {
                this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确')
              })
          } else {
            this.$message.error('请按照指定格式输入')
            return false
          }
        })
      },
      // 删除操作
      handleDelete (index, row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning',
        }).then(() => {
          userdelete(row.id).then((res) => {
            // alert(row.id);
            console.log(res)
            if (res.data.code === 80200) {
              this.$message.success('删除成功')
              // this.tableData.splice(index, 1);
              this.getData()
            } else {
              this.$message.error('删除失败')
              this.getData()
            }
          })
        })
      },

      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },

      // 多选操作
      handleSelectionChange (val) {
        this.multipleSelection = val
      },
      delAllSelection () {
        const length = this.multipleSelection.length
        this.delList = this.delList.concat(this.multipleSelection)
        for (let i = 0; i < length; i++) {
          const str = this.multipleSelection[i].name
          userdelete({ id: this.multipleSelection[i].id })
            .then((res) => {
              console.log(res)
              if (res.data.code === 80200) {
                this.$message.success('删除' + str + '成功')
              } else {
                this.$message.success('删除' + str + '失败')
              }
            })
            .catch(() => {
              this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确')
            })
        }
        this.getData()
        this.multipleSelection = []
      },

      // 触发搜索按钮
      handleSearch () {
        if (this.query.phone == '' && this.query.idcard == '') {
          this.getData()
        } else {
          // this.getData();
          console.log('表单')
          search(1, this.query.phone, this.query.idcard)
            .then((res) => {
              console.log(res)
              if (res.data.code === 80200) {
                console.log(res)
                this.tableData = res.data.data.records
                this.tableData.forEach(item => {
                  item.status = Boolean(item.status)
                })
                this.size = res.data.data.size
                this.total = res.data.data.total
              } else {
                this.$message.error('数据获取失败，' + res.msg)
              }
            })
            .catch(() => {
              this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确')
            })
        }
      },
      handleChange (index, row) {

      },

      // 编辑操作
      handleEdit (index, row) {
        this.idx = index
        this.form = row
        this.editVisible = true
      },
      // 保存编辑
      saveEdit (form) {
        console.log('编辑')
        console.log(this.form)
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.editVisible = false
            let formData = new FormData();
            formData.append('role_id',this.form.roleId)
            formData.append('user_id',this.form.id)
            updateRole(formData)
              .then((res) => {
                console.log(res)

                if (res.data.code === 80200) {
                  // 表示更新成功
                  this.$message.success(`修改第 ${this.idx + 1} 行成功`)
                  this.$set(this.tableData, this.idx, this.form)
                  this.getData()
                } else {
                  // 表示更新失败
                  this.editVisible = false
                  this.$message.error(`修改第 ${this.idx + 1} 行失败`)
                  this.getData()
                }
              })
              .catch(() => {
                this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确')
              })
          } else {
            this.$message.error('请按照指定格式输入')
            return false
          }
        })
      },

      // 查询操作
      handleSelect (row) {
        this.selectVisible = true
        let formData = new FormData;
        formData.append('id',row.id)
        console.log(row.id)
        userview(formData).then((res) =>{
          console.log(res)
          if (res.data.code === 80200) {
            this.tableData = [];
            this.tableData.push(res.data.data);
            //this.tableData.splice(index, 1);

          } else {
            this.$message.error('查询失败');
            this.getData();
          }
        });
        }
        // alert('查询操作');
      },
      // 分页导航
      handlePageChange (val) {
        alert('请求的页数：' + val)

        // 调用方法：this.$set( target, key, value )
        // target：要更改的数据源(可以是对象或者数组)
        // key：要更改的具体数据
        // value ：重新赋的值
        this.$set(this.query, 'currentPage', val)
        this.getData(val)
      },

  }

</script>

<style scoped>

</style>
